/*
//   Copyright 2008 Dear Soft(http://dear-soft.com)
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
 */

package com.dear.soft.components.util;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;

import javax.swing.JDialog;
import javax.swing.JFrame;

public class DialogUtil {

	public static void centerDialogInContainer(JDialog dialog, Container owner) {
		int x;
		int y;
		Point topLeft = owner.getLocationOnScreen();
		Dimension parentSize = owner.getSize();
		Dimension ownSize = dialog.getSize();
		if (parentSize.width > ownSize.width) {
			x = ((parentSize.width - ownSize.width) / 2) + topLeft.x;
		} else {
			x = topLeft.x;
		}
		if (parentSize.height > ownSize.height) {
			y = ((parentSize.height - ownSize.height) / 2) + topLeft.y;
		} else {
			y = topLeft.y;
		}
		dialog.setLocation(x, y);
	}

	public static void centerDialogInParent(JDialog dialog) {
		if (dialog.getParent() != null) {
			centerDialogInContainer(dialog, dialog.getParent());
		} else {
			centerWindowInScreen(dialog);
		}
	}

	public static void centerWindowInScreen(Window window) {
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension mfSize = window.getSize();
		window.setLocation((screenSize.width - mfSize.width) / 2,
				(screenSize.height - mfSize.height) / 2);
	}


	public static void showModalResizableDialog(JDialog dialog, JFrame mainFrame) {
		DialogUtil.centerDialogInContainer(dialog, mainFrame);
		dialog.setModal(true);
		dialog.setResizable(true);
		dialog.setVisible(true);
	}

}
